/*
 * AdaptSysView.java
 */
package pobicos;

import edu.uci.ics.jung.visualization.LayeredIcon;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import javax.swing.SpringLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * The application's main frame.
 */
public class AdaptSysView extends FrameView {

    private JungTreePanel graphicTree_;
    private ArrayList<AgentType> agentTypesList_;
     static final int MIN_WIDTH = 710;
     static final int MIN_HEIGHT = 445;

    public AdaptSysView(SingleFrameApplication app) {

        super(app);
        initComponents();
        int offset = 5;
        agentTypesList_ = new ArrayList<AgentType>();

        openSubtreeNodeEditorButton.setEnabled(false);
        openClickHappinessButton.setEnabled(false);
        isMultipleCheckBox.setEnabled(false);
        isMultipleCheckBox.setSelected(false);

        graphicTree_ = new JungTreePanel(this);
        graphicTree_.setUpTheTree(MainTreePanel.getPreferredSize().width, MainTreePanel.getPreferredSize().height);

        MainTreePanel.setLayout(new BorderLayout());
        MainTreePanel.add(graphicTree_.getTreeJPanel(), BorderLayout.CENTER);
        readAgentTypesFile();

        (this.getFrame()).addComponentListener(new ComponentListener() {

            public void componentResized(ComponentEvent e) {
                graphicTree_.vvSetSize(MainTreePanel.getWidth() - 20, MainTreePanel.getHeight() - 60);
                int width = AdaptSysView.this.getFrame().getWidth();
                int height = AdaptSysView.this.getFrame().getHeight();
                //we check if either the width or the height are below minimum
                boolean resize = false;
                if (width < MIN_WIDTH) {
                    resize = true;
                    width = MIN_WIDTH;
                }
                if (height < MIN_HEIGHT) {
                    resize = true;
                    height = MIN_HEIGHT;
                }
                if (resize) {
                    AdaptSysView.this.getFrame().setSize(width, height);
                    AdaptSysView.this.getFrame().repaint();
                }
            }
            public void componentMoved(ComponentEvent e) {
            }
            public void componentShown(ComponentEvent e) {
            }
            public void componentHidden(ComponentEvent e) {
            }
        });
    }

    public void addTypeToList(AgentType type) {
        agentTypesList_.add(type);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = AdaptSysApp.getApplication().getMainFrame();
            aboutBox = new AdaptSysAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        AdaptSysApp.getApplication().show(aboutBox);
    }

    private void readAgentTypesFile() {
        File f1 = new File("agentsList.txt");
        if (f1.exists()) {
            try {
                BufferedReader datas = new BufferedReader(new FileReader("agentsList.txt"));
                /**
                 * Counts number of lines in the file
                 */
                Scanner input = new Scanner(f1);
                int agentsCounter = 0;
                while (input.hasNextLine()) {
                    input.nextLine();
                    agentsCounter++;
                }
                System.out.println("Number of lines: " + agentsCounter);
                for (int i = 0; i < agentsCounter; ++i) {
                    String s = datas.readLine();
                    StringTokenizer t = new StringTokenizer(s, ";");
                    String agentTypeName = t.nextToken();
                    ArrayList<String> tempGoalsArray = new ArrayList<String>();
                    int numberOfGoals = Integer.parseInt(t.nextToken());
                    for (int j = 0; j < numberOfGoals; ++j) {
                        String goal = t.nextToken();
                        tempGoalsArray.add(goal);
                    }
                    addTypeToList(new AgentType(agentTypeName, tempGoalsArray));
                    AddTypeComboBox.addItem(agentTypeName);
                }
                AddTypeComboBox.setEnabled(true);
                datas.close();
            } catch (IOException exc) {
                JOptionPane.showMessageDialog(null, "Error while reading from file!\n");
            }
        } else {
            JOptionPane.showMessageDialog(null, "File with agent types does not exist\n");
        }
    }
//    @Action
//    public void showNodeEditor() {
//        if (nodeEitorFrame == null) {
//            nodeEitorFrame = new NodeEditorFrame();
//        }
//        AdaptSysApp.getApplication().show(nodeEitorFrame);
//    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        MainTreePanel = new javax.swing.JPanel();
        buttonPanel = new javax.swing.JPanel();
        ComputeHappinessButton = new javax.swing.JButton();
        loadSessionButton = new javax.swing.JButton();
        saveSessionButton = new javax.swing.JButton();
        openSubtreeNodeEditorButton = new javax.swing.JButton();
        AgentTypeEditorButton = new javax.swing.JButton();
        AssaignAgentTypeButton = new javax.swing.JButton();
        AddTypeComboBox = new javax.swing.JComboBox();
        isMultipleCheckBox = new javax.swing.JCheckBox();
        openClickHappinessButton = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();

        mainPanel.setName("mainPanel"); // NOI18N

        MainTreePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        MainTreePanel.setName("MainTreePanel"); // NOI18N

        javax.swing.GroupLayout MainTreePanelLayout = new javax.swing.GroupLayout(MainTreePanel);
        MainTreePanel.setLayout(MainTreePanelLayout);
        MainTreePanelLayout.setHorizontalGroup(
            MainTreePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 476, Short.MAX_VALUE)
        );
        MainTreePanelLayout.setVerticalGroup(
            MainTreePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 450, Short.MAX_VALUE)
        );

        buttonPanel.setName("buttonPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(pobicos.AdaptSysApp.class).getContext().getResourceMap(AdaptSysView.class);
        ComputeHappinessButton.setText(resourceMap.getString("ComputeHappinessButton.text")); // NOI18N
        ComputeHappinessButton.setDoubleBuffered(true);
        ComputeHappinessButton.setName("ComputeHappinessButton"); // NOI18N
        ComputeHappinessButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ComputeHappinessButtonActionPerformed(evt);
            }
        });

        loadSessionButton.setFont(resourceMap.getFont("loadSessionButton.font")); // NOI18N
        loadSessionButton.setText(resourceMap.getString("loadSessionButton.text")); // NOI18N
        loadSessionButton.setDoubleBuffered(true);
        loadSessionButton.setName("loadSessionButton"); // NOI18N
        loadSessionButton.setPreferredSize(new java.awt.Dimension(150, 40));
        loadSessionButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                loadSessionButtonMouseClicked(evt);
            }
        });

        saveSessionButton.setText(resourceMap.getString("saveSessionButton.text")); // NOI18N
        saveSessionButton.setDoubleBuffered(true);
        saveSessionButton.setName("saveSessionButton"); // NOI18N
        saveSessionButton.setPreferredSize(new java.awt.Dimension(150, 40));
        saveSessionButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                saveSessionButtonMousePressed(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(pobicos.AdaptSysApp.class).getContext().getActionMap(AdaptSysView.class, this);
        openSubtreeNodeEditorButton.setAction(actionMap.get("showNodeEditor")); // NOI18N
        openSubtreeNodeEditorButton.setText(resourceMap.getString("openSubtreeNodeEditorButton.text")); // NOI18N
        openSubtreeNodeEditorButton.setDoubleBuffered(true);
        openSubtreeNodeEditorButton.setName("openSubtreeNodeEditorButton"); // NOI18N
        openSubtreeNodeEditorButton.setPreferredSize(new java.awt.Dimension(150, 40));
        openSubtreeNodeEditorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openSubtreeNodeEditorButtonActionPerformed(evt);
            }
        });

        AgentTypeEditorButton.setAction(actionMap.get("showNodeEditor")); // NOI18N
        AgentTypeEditorButton.setText(resourceMap.getString("AgentTypeEditorButton.text")); // NOI18N
        AgentTypeEditorButton.setDoubleBuffered(true);
        AgentTypeEditorButton.setName("AgentTypeEditorButton"); // NOI18N
        AgentTypeEditorButton.setPreferredSize(new java.awt.Dimension(150, 40));
        AgentTypeEditorButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                AgentTypeEditorButtonMouseClicked(evt);
            }
        });

        AssaignAgentTypeButton.setText(resourceMap.getString("AssaignAgentTypeButton.text")); // NOI18N
        AssaignAgentTypeButton.setEnabled(false);
        AssaignAgentTypeButton.setName("AssaignAgentTypeButton"); // NOI18N
        AssaignAgentTypeButton.setPreferredSize(new java.awt.Dimension(150, 40));
        AssaignAgentTypeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AssaignAgentTypeButtonActionPerformed(evt);
            }
        });

        AddTypeComboBox.setEnabled(false);
        AddTypeComboBox.setName("AddTypeComboBox"); // NOI18N

        isMultipleCheckBox.setFont(resourceMap.getFont("isMultipleCheckBox.font")); // NOI18N
        isMultipleCheckBox.setText(resourceMap.getString("isMultipleCheckBox.text")); // NOI18N
        isMultipleCheckBox.setName("isMultipleCheckBox"); // NOI18N
        isMultipleCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                isMultipleCheckBoxActionPerformed(evt);
            }
        });

        openClickHappinessButton.setAction(actionMap.get("showNodeEditor")); // NOI18N
        openClickHappinessButton.setText(resourceMap.getString("openClickHappinessButton.text")); // NOI18N
        openClickHappinessButton.setDoubleBuffered(true);
        openClickHappinessButton.setName("openClickHappinessButton"); // NOI18N
        openClickHappinessButton.setPreferredSize(new java.awt.Dimension(150, 40));
        openClickHappinessButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openClickHappinessButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout buttonPanelLayout = new javax.swing.GroupLayout(buttonPanel);
        buttonPanel.setLayout(buttonPanelLayout);
        buttonPanelLayout.setHorizontalGroup(
            buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(loadSessionButton, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addGap(11, 11, 11))
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(isMultipleCheckBox, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                    .addComponent(saveSessionButton, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonPanelLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(AgentTypeEditorButton, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonPanelLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(openSubtreeNodeEditorButton, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(AddTypeComboBox, 0, 142, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(AssaignAgentTypeButton, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(openClickHappinessButton, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addGap(11, 11, 11))
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ComputeHappinessButton, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addGap(11, 11, 11))
        );
        buttonPanelLayout.setVerticalGroup(
            buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(loadSessionButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(saveSessionButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(isMultipleCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(AgentTypeEditorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(openSubtreeNodeEditorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(AssaignAgentTypeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(AddTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
                .addComponent(openClickHappinessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ComputeHappinessButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(MainTreePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(MainTreePanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        menuBar.setDoubleBuffered(true);
        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    private void loadSessionButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_loadSessionButtonMouseClicked

        JFileChooser chooser = new JFileChooser();
        try {
            // Create a File object containing the canonical path of the desired directory
            File f = new File(new File(".").getCanonicalPath() + "/graph_sessions");
            // Set the current directory
            chooser.setCurrentDirectory(f);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("JUNG .graphml", "graphml");
            chooser.setFileFilter(filter);

        } catch (IOException e) {
        }
        int returnVal = chooser.showOpenDialog(AdaptSysView.this.getComponent());

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            //This is where a real application would open the file.

            //=================LOADING LOGICAL TREE==================
            HashMap<Integer, Agent> ar = null;
            try {
                StringTokenizer st = new StringTokenizer(file.getName(), ".");
                FileInputStream fis = new FileInputStream("graph_sessions/" + st.nextToken() + ".dat");
                ObjectInputStream ois = new ObjectInputStream(fis);

                ar = (HashMap<Integer, Agent>) ois.readObject();
//                for (Agent a : ar) {
//                    System.out.println(" Pokaz co przeczytales: " + a.getId() + a.getType().getAgentTypeName());
//                }

                ois.close();

            } catch (IOException o) {
            } catch (ClassNotFoundException o) {
            }
            //================LOADING GRAPHICAL TREE WITH LOGICAL TREE AGENTS LIST====================
            try {
                graphicTree_.readFromGraphmlFile("graph_sessions/" + file.getName(), ar);
            } catch (IOException o) {
                System.out.println("ERROR1" + o.getMessage());
            } catch (ParserConfigurationException o) {
                System.out.println("ERROR2" + o.getMessage());
            } catch (SAXException o) {
                System.out.println("ERROR3" + o.getMessage());
            }
        } else {
            System.out.println("Open command cancelled by user.");
        }
    }//GEN-LAST:event_loadSessionButtonMouseClicked

    private void saveSessionButtonMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveSessionButtonMousePressed
        JFileChooser chooser = new JFileChooser();
        try {
            // Create a File object containing the canonical path of the desired directory
            File f = new File(new File(".").getCanonicalPath() + "/graph_sessions");
            // Set the current directory
            chooser.setCurrentDirectory(f);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("JUNG .graphml", "graphml");
            chooser.setFileFilter(filter);

        } catch (IOException e) {
        }
        int returnVal = chooser.showSaveDialog(AdaptSysView.this.getComponent());
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            File file = chooser.getSelectedFile();
            int choice = JOptionPane.YES_OPTION;
            if (file.exists()) {
                Object[] possibilities = {"Yes", "No"};
                choice = JOptionPane.showOptionDialog(this.getFrame(), "Selected file name already exitst. Do you want to overwirte?",
                        "Save session", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, possibilities, possibilities[0]);
            }
            if (choice == JOptionPane.YES_OPTION) {
                //=================SAVING LOGICAL TREE==================
                try {
                    StringTokenizer st = new StringTokenizer(file.getName(), ".");
                    FileOutputStream fos = new FileOutputStream("graph_sessions/" + st.nextToken() + ".dat");

                    ObjectOutputStream oos = new ObjectOutputStream(fos);

                    HashMap<Integer, Agent> temMap = new HashMap<Integer, Agent>();
                    for (Integer i : graphicTree_.getGraph().getVertices()) {
                        Agent tempAgent = (Agent) graphicTree_.getLogicalTree().getNodeAt(i).getData();
                        Agent agent = new Agent(tempAgent);
                        temMap.put(tempAgent.getId(), agent);
                    }
                    oos.writeObject(temMap);
                    oos.flush();
                    oos.close();

                    JOptionPane.showMessageDialog(null, "Session sucesfully saved!");

                } catch (FileNotFoundException w) {
                } catch (IOException w) {
                }
                //=================SAVING GRAPHIC TREE==================
                try {
                    graphicTree_.saveToGraphmlFile("graph_sessions/" + file.getName());
                } catch (IOException o) {
                }
            } else {
                System.out.println("Try another name.");
            }
        } else {
            System.out.println("Open command cancelled by user.");
        }
    }//GEN-LAST:event_saveSessionButtonMousePressed

    private void AgentTypeEditorButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AgentTypeEditorButtonMouseClicked
        new AgentTypeEditor(this).setVisible(true);
    }//GEN-LAST:event_AgentTypeEditorButtonMouseClicked

    private void AssaignAgentTypeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AssaignAgentTypeButtonActionPerformed
        Agent tempAgent = (Agent) graphicTree_.getLogicalTree().getNodeAt(graphicTree_.currentPickedVertex).getData();
        if (tempAgent.getType() != null && tempAgent.getHappinessMap()!=null) {
             JOptionPane.showMessageDialog(null, "Happiness already set - cannot change type");
        } else {
            tempAgent.setType(agentTypesList_.get(AddTypeComboBox.getSelectedIndex()));
            graphicTree_.getLogicalTree().getNodeAt(graphicTree_.currentPickedVertex).setData(tempAgent);
            graphicTree_.getAssaingedVertexList().add(graphicTree_.currentPickedVertex);
            graphicTree_.getPickedState().clear(); 
        }
    }//GEN-LAST:event_AssaignAgentTypeButtonActionPerformed

    private void openSubtreeNodeEditorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openSubtreeNodeEditorButtonActionPerformed
        graphicTree_.getPickedState().clear();
        new SubtreeEditor(graphicTree_).setVisible(true);
    }//GEN-LAST:event_openSubtreeNodeEditorButtonActionPerformed

    private void isMultipleCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_isMultipleCheckBoxActionPerformed
        if (isMultipleCheckBox.isSelected()) {
            new MultipleNodeEditor(graphicTree_).setVisible(true);
        } else {
            MyNode<Agent> tempPickedNode = graphicTree_.getLogicalTree().getNodeAt(graphicTree_.currentPickedVertex);
            tempPickedNode.getData().setSingleMode();
            graphicTree_.getMultipleNodeCollection().remove(graphicTree_.currentPickedVertex);
        }
    }//GEN-LAST:event_isMultipleCheckBoxActionPerformed

    private void openClickHappinessButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openClickHappinessButtonActionPerformed
        Agent tempAgent = (Agent) graphicTree_.getLogicalTree().getNodeAt(graphicTree_.currentPickedVertex).getData();
        if (tempAgent.getType() != null) {
            new ClickHappinessEditor(graphicTree_).setVisible(true);
        } else {
            JOptionPane.showMessageDialog(null, "Agent must have type assigned.");
        }
    }//GEN-LAST:event_openClickHappinessButtonActionPerformed

    private void ComputeHappinessButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ComputeHappinessButtonActionPerformed
      
        //creating list of all operators for current application
        List<Operator> allOperarsList = new ArrayList<Operator>();
        
        for(Integer i : graphicTree_.getGraph().getVertices()) {
            Agent tempAgent = (Agent) graphicTree_.getLogicalTree().getNodeAt(i).getData();
            if(tempAgent.getOperatorsList()!=null) {
                allOperarsList.addAll(tempAgent.getOperatorsList());
            }
        }
        
        for(Operator o : allOperarsList ) {
             Map<String,Double> td = new HashMap<String, Double> ();
                for(String goal : o.getInputs()) {
                    StringTokenizer st = new StringTokenizer(goal, ".");
                    Integer index = Integer.parseInt(st.nextToken());  System.out.println("Index : " + index);
                    String postIndex = st.nextToken();                 System.out.println("postIndex : " + postIndex);
                    String goalName = st.nextToken();                  System.out.println("goalName : " + goalName);
                    Agent tempChildAgent = (Agent) graphicTree_.getLogicalTree().getNodeAt(index).getData();
                    String key= postIndex+"."+goalName;
                    td.put(goal,tempChildAgent.getHappinessMap().get(key));               
                }
                for(String destGoal :  o.getOutputs()) {
                    StringTokenizer st = new StringTokenizer(destGoal, ".");
                    Integer index = Integer.parseInt(st.nextToken());  System.out.println("Output Index : " + index);
                    String postIndex = st.nextToken();                 System.out.println("Output postIndex : " + postIndex);
                    String goalName = st.nextToken();                  System.out.println("Output goalName : " + goalName);
                String finalGoal = postIndex + "." + goalName;
                /**
                 * Computing happiness, but propably in other function than that one above:
                 */
                double computedGoalHappiness = AdaptationComputer.computeHappinessForSingleOperator(o.getFileImplName(), td);
                //
                Agent tempAgent = (Agent) graphicTree_.getLogicalTree().getNodeAt(index).getData();
                
                if (tempAgent.getHappinessMap() != null) {
                    tempAgent.getHappinessMap().put(finalGoal, computedGoalHappiness);
                } else {
                    Map<String, Double> tempMap = new HashMap<String, Double>();
                    tempMap.put(finalGoal, computedGoalHappiness);
                    tempAgent.setHappinessMap(tempMap);
                }
            //    tempAgent.getHappinessMap().put(finalGoal, computedGoalHappiness);
            }               
        }
        graphicTree_.repaintVV();
    }//GEN-LAST:event_ComputeHappinessButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public static javax.swing.JComboBox AddTypeComboBox;
    public static javax.swing.JButton AgentTypeEditorButton;
    public static javax.swing.JButton AssaignAgentTypeButton;
    private javax.swing.JButton ComputeHappinessButton;
    public javax.swing.JPanel MainTreePanel;
    private javax.swing.JPanel buttonPanel;
    public static javax.swing.JCheckBox isMultipleCheckBox;
    public static javax.swing.JButton loadSessionButton;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    public static javax.swing.JButton openClickHappinessButton;
    public static javax.swing.JButton openSubtreeNodeEditorButton;
    public static javax.swing.JButton saveSessionButton;
    // End of variables declaration//GEN-END:variables
    private JDialog aboutBox;
}
